package com.atomscat.lottery.controller.wx;

import com.atomscat.lottery.service.ReceiveWeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

/**
 * flow 微信 -> 扫码 => 返回授权url => 微信 -> 授权 => 返回code => 微信 -> 获取access_token => 微信 -> 获取用户信息
 *
 * @author Edward
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/wechat/redirect/{appid}")
public class WxRedirectController {

    private final WxMpService wxService;
    private final ReceiveWeChatService receiveWeChatService;

    @Value("${redirect.lottery.url}")
    private String redirectLotteryUrl;

    /**
     * Handles the redirection for a lottery activity.
     *
     * @param appid The WeChat app ID.
     * @param lotteryActivityId The ID of the lottery activity.
     * @param code The authorization code received from WeChat.
     * @param response The server HTTP response used to set the redirection.
     * @return A string indicating the user greeting process.
     * @throws IllegalArgumentException If the app ID configuration is not found.
     */
    @GetMapping("/lottery/{lotteryActivityId}")
    public String greetUser(@PathVariable String appid, @PathVariable Long lotteryActivityId, @RequestParam String code, ServerHttpResponse response) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        receiveWeChatService.greetUserToMq(appid, lotteryActivityId, code);
        response.setStatusCode(HttpStatus.FOUND); // 302 临时重定向'
        response.getHeaders().setLocation(URI.create(redirectLotteryUrl));
        return "greet user";
    }
}
